import { setToken, getToken } from '@/utils/auth'
import { login, getProfile } from '@/api/user'

import { resetRouter } from '@/router/index'
const state = {
  userInfo: {},
  token: getToken() || null
}

const mutations = {
  setToken: function(state, newToken) {
    // 保存到vuex
    state.token = newToken

    // 保存到cookie
    setToken(newToken)
  },

  setUserInfo(state, newInfo) {
    state.userInfo = newInfo
  }
}

const actions = {

  logout(context) {
    // 做退出的操作
    // 清空 token, 个人信息
    context.commit('setToken', '')
    context.commit('setUserInfo', {})

    // 重置路由
    resetRouter()
  },

  async getProfile(context) {
    // 假设拿到数据
    const result = await getProfile()
    // console.log('getProfile......', result)

    // 调用mutation
    console.log('getProfile......', result.data)

    // 调用mutation
    context.commit('setUserInfo', result.data)
    // 返回
    return result.data
  },
  // 登录
  async login(context, payload) {
    const result = await login(payload)
    const token = result.data
    // 在action中调用mutation
    context.commit('setToken', token)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
